package com.library.bookmanagement.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.library.bookmanagement.entity.*;
import com.library.bookmanagement.mapper.*;
import com.library.bookmanagement.service.UserService;
import com.library.bookmanagement.util.Constant;
import com.library.bookmanagement.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：ZXM
 * @date ：Created in 2020/5/11 15:37
 * @description：读者service接口实现类
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private BookSituationMapper bookSituationMapper;
    @Autowired
    private ReadMapper readMapper;
    @Autowired
    private ReserveMapper reserveMapper;
    @Autowired
    private OverdueMapper overdueMapper;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;



    /**
    * @Description: 借阅书籍
    * @Param: [userId, bookId]
    * @return: com.library.bookmanagement.util.ResultUtil
    * @Author: ZXM
    * @Date: 2020/6/10
    */
    @Override
    public ResultUtil borrowBookByReadKey(Integer userId, Integer bookId) {
        Book book = bookMapper.selectByPrimaryKey(bookId);
        ReaderKey readKey = new ReaderKey(userId, bookId);
        Read read1 = readMapper.selectByPrimaryKey(readKey);
        // 判断借阅信息中有无重复借阅的情况
        if(read1 != null && read1.getBackTime().compareTo(new Date(System.currentTimeMillis()))==1){
            return ResultUtil.error().message("您不能重复借阅同一本书籍!");
        }
        if(book != null && book.getbCount() > 0){
            User user = userMapper.selectByPrimaryKey(userId);
            user.setuNumber(user.getuNumber()+1);
            Read read = new Read();
            read.setUserId(userId);
            read.setBookId(bookId);
            read.setLendTime(new Date(System.currentTimeMillis()));
            long thirty = 2592000000L;
            read.setBackTime(new Date((System.currentTimeMillis()+thirty)));
            read.setBackBool(0);
            readMapper.insertSelective(read);
            book.setBorrowCount(book.getBorrowCount()+1);
            book.setbCount(book.getbCount()-1);
            bookMapper.updateByPrimaryKeySelective(book);
            ReaderKey reserveKey = new ReaderKey(userId, bookId);
            Reserve reserve = reserveMapper.selectByPrimaryKey(reserveKey);
            // 将预定中的记录清除掉
            if(reserve != null){
                reserveMapper.deleteByPrimaryKey(reserveKey);
            }
            return ResultUtil.ok().message("图书借阅成功!");
        }else if(book.getbCount() == 0){
            return ResultUtil.error().message("当前图书已被借完，无法完成借阅!");
        }else{
            return ResultUtil.error().message("图书借阅失败");
        }
    }

    /**
    * @Description: 修改用户
    * @Param: [user]
    * @return: com.library.bookmanagement.util.ResultUtil
    * @Author: ZXM
    * @Date: 2020/6/10
    */
    @Override
    public ResultUtil editUserById(User user) {
        userMapper.updateByPrimaryKeySelective(user);
        return ResultUtil.ok().message("用户修改信息成功");
    }

    /**
    * @Description: 显示借阅记录
    * @Param: [pageNum, pageSize, userId]
    * @return: com.library.bookmanagement.util.ResultUtil<java.util.Map<java.lang.String,java.lang.Object>>
    * @Author: ZXM
    * @Date: 2020/6/10
    */
    @Override
    public ResultUtil<Map<String,Object>> queryReadListByUserId(Integer pageNum, Integer pageSize, Integer userId) {
        PageHelper.startPage(pageNum,pageSize);
        Page<Read> reads = readMapper.selectByUserKey(userId);
        if(reads != null){
            HashMap<String,Object> map = new HashMap<>();
            map.put(Constant.MESSAGE_TOTALNUM,reads.getTotal());
            map.put(Constant.MEASSAGE_DATAS,reads);
        }else{
            ResultUtil.error().message("当前用户暂无阅读记录");
        }
        return ResultUtil.ok().data(reads);
    }

    /**
    * @Description: 归还图书
    * @Param: [userId, bookId]
    * @return: com.library.bookmanagement.util.ResultUtil
    * @Author: ZXM
    * @Date: 2020/6/10
    */
    @Override
    public ResultUtil backBookByReadKey(Integer userId, Integer bookId) {
        ReaderKey readKey = new ReaderKey(userId, bookId);
        Read read = readMapper.selectByPrimaryKey(readKey);
        if(read != null){
            read.setBackTime(new Date(System.currentTimeMillis()));
            Book book = bookMapper.selectByPrimaryKey(bookId);
            if(book != null){
                book.setbCount(book.getbCount()+1);
                bookMapper.updateByPrimaryKeySelective(book);
                read.setBackTime(new Date(System.currentTimeMillis()));
                read.setBackBool(1);
                readMapper.updateByPrimaryKeySelective(read);
                return ResultUtil.ok().message("还书成功");
            }else{
                return ResultUtil.error().message("还书失败!");
            }
        }else{
            return ResultUtil.error().message("未找到当前书籍借阅记录!");
        }
    }

    /**
    * @Description: 预定图书
    * @Param: [userId, bookId]
    * @return: com.library.bookmanagement.util.ResultUtil
    * @Author: ZXM
    * @Date: 2020/6/10
    */
    @Override
    public ResultUtil reserveBookByReserveKey(Integer userId, Integer bookId) {
        Book book = bookMapper.selectByPrimaryKey(bookId);
        if(book.getbCount() > 0){
            return ResultUtil.error().message("当前图书还有剩余，请直接前往借阅!");
        }
        // 用户判断是否出现重复预定的情况
        ReaderKey reserveKey = new ReaderKey();
        reserveKey.setUserId(userId);
        reserveKey.setBookId(bookId);
        Reserve reserve1 = reserveMapper.selectByPrimaryKey(reserveKey);
        if(reserve1 != null){
            return ResultUtil.error().message("您不能重复预定同一书籍!");
        }else{
            Integer integer = reserveMapper.selectCountByBookId(bookId);
            if(integer < 3 && integer >= 0){
                Reserve reserve = new Reserve();
                reserve.setUserId(userId);
                reserve.setBookId(bookId);
                reserve.setStartTime(new Date(System.currentTimeMillis()));
                long seven = 604800000L;
                reserve.setLastTime(new Date(System.currentTimeMillis()+seven));
                reserveMapper.insertSelective(reserve);
                return ResultUtil.ok().message("预定书籍成功!");
            }else{
                return ResultUtil.error().message("当前书籍预定人数较多，请耐心等待...");
            }
        }
    }

    /**
    * @Description: 预定列表
    * @Param: [userId]
    * @return: com.library.bookmanagement.util.ResultUtil<java.util.List<com.library.bookmanagement.entity.Reserve>>
    * @Author: ZXM
    * @Date: 2020/6/10
    */
    @Override
    public ResultUtil<List<Reserve>> queryReserveListByUserId(Integer userId) {
        List<Reserve> reserves = reserveMapper.selectByUserId(userId);
        if(reserves != null){
            return ResultUtil.ok().data(reserves);
        }
        return ResultUtil.error().message("您没有预定书籍!");
    }

    /**
    * @Description: 取消预定
    * @Param: [userId, bookId]
    * @return: com.library.bookmanagement.util.ResultUtil
    * @Author: ZXM
    * @Date: 2020/6/10
    */
    @Override
    public ResultUtil cancelReserveByKey(Integer userId, Integer bookId) {
        ReaderKey reserveKey = new ReaderKey();
        reserveKey.setBookId(bookId);
        reserveKey.setUserId(userId);
        Reserve reserve = reserveMapper.selectByPrimaryKey(reserveKey);
        if(reserve != null){
            reserveMapper.deleteByPrimaryKey(reserveKey);
            return ResultUtil.ok().message("取消预定成功");
        }else{
            return ResultUtil.error().message("该预定信息不存在!");
        }
    }

    /**
    * @Description: 根据用户名查询用户
    * @Param: [username]
    * @return: com.library.bookmanagement.util.ResultUtil<com.library.bookmanagement.entity.User>
    * @Author: ZXM
    * @Date: 2020/6/10
    */
    @Override
    public ResultUtil<User> queryUserByName(String username) {
        User user = userMapper.selectByName(username);
        if(user != null){
            return ResultUtil.ok().data(user);
        }else{
            return ResultUtil.error().message("用户信息返回失败!");
        }
    }

    /**
    * @Description: 读者修改密码
    * @Param: [userId, oldPassword, newPassword]
    * @return: com.library.bookmanagement.util.ResultUtil
    * @Author: ZXM
    * @Date: 2020/6/10
    */
    @Override
    public ResultUtil editUserPassword(Integer userId,String oldPassword,String newPassword) {
        User user = userMapper.selectByPrimaryKey(userId);
        boolean isPass = bCryptPasswordEncoder.matches(oldPassword, user.getuPassword());
        if(!isPass){
            return ResultUtil.error().message("旧密码不匹配!");
        }else{
            user.setuPassword(bCryptPasswordEncoder.encode(newPassword));
            userMapper.updateByPrimaryKeySelective(user);
            return ResultUtil.ok().message("密码修改成功!");
        }
    }

    /**
    * @Description: 修改用户头像
    * @Param: [username, filename]
    * @return: void
    * @Author: ZXM
    * @Date: 2020/6/19
    */
    @Override
    public void editUserImg(String username, String filename) {
        User user = userMapper.selectByName(username);
        user.setuImg(filename);
        userMapper.updateByPrimaryKeySelective(user);
    }

    /**
    * @Description: 返回用户逾期记录
    * @Param: [userId]
    * @return: com.library.bookmanagement.util.ResultUtil<java.util.List<com.library.bookmanagement.entity.Overdue>>
    * @Author: ZXM
    * @Date: 2020/6/19
    */
    @Override
    public ResultUtil<List<Overdue>> overdueListByUserId(Integer userId) {
        List<Overdue> overdueList = overdueMapper.selectByUserId(userId);
        if(overdueList != null){
            return ResultUtil.ok().data(overdueList);
        }
        return ResultUtil.error().message("当前用户暂无逾期归还的记录");
    }

    /**
    * @Description: 用户完成逾期书籍归还
    * @Param: [overdueKey]
    * @return: com.library.bookmanagement.util.ResultUtil
    * @Author: ZXM
    * @Date: 2020/6/19
    */
    @Override
    public ResultUtil backOverdueBookByKey(ReaderKey overdueKey) {
        Overdue overdue = overdueMapper.selectByPrimaryKey(overdueKey);
        Book book = overdue.getBook();
        book.setbCount(book.getbCount()+1);
        overdue.setLastTime(new Date(System.currentTimeMillis()));
        int day = (int) ((overdue.getLastTime().getTime()-overdue.getStartTime().getTime())/(1000 * 60 * 60 * 24));
        overdue.setOverdueTime(day+"");
        int i = overdueMapper.updateByPrimaryKeySelective(overdue);
        if(i != -1){
            return ResultUtil.ok().message("逾期归还图书成功!");
        }
        return ResultUtil.error().message("逾期归还图书失败!");
    }
}
